package com.aishare.qicaitaoke.network.upLoadFile;

import android.net.Network;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.aishare.qicaitaoke.utils.KLog;
import com.aishare.qicaitaoke.utils.coreprogress.helper.ProgressHelper;
import com.aishare.qicaitaoke.utils.coreprogress.listener.impl.UIProgressListener;
import com.google.gson.Gson;


import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * 作者 陆文明
 * 时间 2017/6/14
 */

public class UpLoadFileManager {

    private OkHttpClient okHttpClient;

    private static UpLoadFileManager instance = null;
    private Handler handler;


    public static synchronized UpLoadFileManager getInstance() {
        if (instance == null) {
            instance = new UpLoadFileManager();
        }
        return instance;
    }


    public void uploadFileCommon(String json, List<String> imgs, final Handler handler) {
        this.handler = handler;
        buildHttpClient();
        String url = "https://dev.withbtc.com/report/api/handset/recieve/";
        url = url + "?sign=" + json;
        KLog.e("TAG", "url = " + url);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (imgs != null)
            for (int i = 0; i < imgs.size(); i++) {
                File file = new File(imgs.get(i));
                KLog.e("TAG", "filePath = " + imgs.get(i));
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
                builder.addFormDataPart("img" + i, file.getName(), requestBody);
            }
        MultipartBody multipartBody = builder.build();
        final Request request = new Request.Builder().addHeader("Connection", "keep-alive").url(url).post(ProgressHelper.addProgressRequestListener(multipartBody, uiProgressRequestListener)).build();
        KLog.e("TAG", "commentHeaders = " + request.headers());
        KLog.e("TAG", "url = " + url);

        this.okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                KLog.e("TAG", " json = " + e.toString());
                Message message = new Message();
                message.arg1 = 1003;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson = new Gson();

                Message message = new Message();
                message.arg1 = 1002;
                handler.sendMessage(message);
                KLog.e("TAG", " json = " + json);
            }
        });
    }

    private void buildHttpClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (okHttpClient == null)
            this.okHttpClient = new OkHttpClient.Builder()
//                    .connectTimeout(5000, TimeUnit.MILLISECONDS)
//                    .readTimeout(5000, TimeUnit.MILLISECONDS)
//                    .writeTimeout(5000, TimeUnit.MILLISECONDS)
//                    .addInterceptor(interceptor)
                    .build();
    }

    //这个是ui线程回调，可直接操作UI
    private final UIProgressListener uiProgressRequestListener = new UIProgressListener() {
        @Override
        public void onUIProgress(long bytesWrite, long contentLength, boolean done) {
            KLog.e("TAG", "bytesWrite:" + bytesWrite);
            KLog.e("TAG", "contentLength" + contentLength);
            KLog.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
            KLog.e("TAG", "done:" + done);
            KLog.e("TAG", "================================");
            //ui层回调
//            Toast.makeText(ActivityUtil.INSTANCE.getApplication(),"正在上传", Toast.LENGTH_LONG).show();
            if (handler != null) {
                Message message = new Message();
                message.obj = (100 * bytesWrite) / contentLength + "%";
                message.arg1 = 1000;
                handler.sendMessage(message);
            }
        }

        @Override
        public void onUIStart(long bytesWrite, long contentLength, boolean done) {
            super.onUIStart(bytesWrite, contentLength, done);
//            Toast.makeText(ActivityUtil.INSTANCE.getApplication(), "start", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onUIFinish(long bytesWrite, long contentLength, boolean done) {
            super.onUIFinish(bytesWrite, contentLength, done);
            if (handler != null) {
//                Toast.makeText(ActivityUtil.INSTANCE.getApplication(), "上传完成", Toast.LENGTH_SHORT).show();
                Message message = new Message();
                message.arg1 = 1001;
                handler.sendMessage(message);
            }
        }
    };
}
